02 / 11

How would you design a system for a Car that has different engine types (Petrol, Diesel, Electric)? Show the OOP model.

Difficulty: 3/10

Car and Engine Using Composition

I would model Car and Engine using composition rather than creating separate inheritance hierarchies such as PetrolCar, DieselCar, and ElectricCar. The Car depends on an IEngine abstraction, and concrete engines implement the behavior. This follows programming to an interface and makes adding another engine type possible without modifying Car.

javascript
  1. 1

    Car has an Engine rather than inheriting from an engine.

  2. 2

    The engine abstraction isolates Car from concrete engine implementations.

  3. 3

    New engines can be introduced without modifying Car.

  4. 4

    Dependency injection can select the engine at runtime or configuration time.

  5. 5

    This design supports Open/Closed Principle and composition over inheritance.

Follow-up Questions

  • How would you add hybrid engines?
  • Would you use Factory or Strategy here?
  • How would you test Car without a real engine?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.